export default {
  data () {
    return {
      clientLog: {
        startTime: null,
        currentTime: null,
        currentPath: ''
      }
    }
  },
  created () {
    this.clientLog.startTime = Date.now()
    window.addEventListener('beforeunload', this.GetResidenceTime)
    this.clientLog.currentPath = this.$route.fullPath
  },
  beforeDestroy () {
    this.clientLog.currentTime = Date.now()
    this.GetResidenceTime()
    window.removeEventListener('beforeunload', this.GetResidenceTime)
  },
  methods: {
    async GetResidenceTime () {
      const { startTime, currentTime } = this.clientLog
      let log = {
        email: this.$store.state.user.email,
        browser: this.browserType(),
        pageViewed: this.clientLog.currentPath,
        duration: parseInt(((currentTime === null ? Date.now() : currentTime) - startTime) / 1000),
        ip: localStorage.getItem('Ip')
      }
      if (log.duration > 0) await this.$interface.system.clientLogApi(log)
    },
    browserType () {
      var explorer = navigator.userAgent
      if (explorer.indexOf('MSIE') >= 0) {
        return 'ie'
      } else if (explorer.indexOf('Firefox') >= 0) {
        return 'Firefox'
      } else if (explorer.indexOf('Chrome') >= 0) {
        return 'Chrome'
      } else if (explorer.indexOf('Opera') >= 0) {
        return 'Opera'
      } else if (explorer.indexOf('Safari') >= 0) {
        return 'Safari'
      } else if (explorer.indexOf('Netscape') >= 0) {
        return 'Netscape'
      }
    }
  }
}
